/**
 * @description 历史内容区域
 */
import { QTabPanel, useQuasar } from '@teld/q-components';
// import QTabPanel from 'quasar/src/components/tabs/QTabPanel';
// import {
//   TInput as Field,
//   TDateTime as TmDatePick,
//   TDateTime as TmDateTimePick,
//   TIcon as TmIcon,
//   TSelect as TmSelect,
//   TSlider as TmSlider,
//   TTabs as TmTabs,
//   TChip as TmTag
// } from 't';
import Field from 't/basic/input';
import TInputNumber from 't/basic/inputNumber';
import TmDatePick from 't/basic/date-time'
import TmDateTimePick from 't/basic/date-time'
import TmIcon from 't/basic/icon';
import TmSelect from 't/basic/select';
import TmSlider from 't/basic/slider';
import TmTabs from 't/basic/tabs';
import TmTag from 't/basic/chip';
import TmSelectHelper from '../../../select-helper/Component';
import TmPopover from '../popover';
import { Terms } from '../../../filter/config/resouce';
import { defineComponent, nextTick, onMounted, ref, toRefs, watch } from 'vue';
/**
 * Component for filtering content.
 *
 * @component
 * @example
 * <FilterContent
 *   :plan="plan"
 *   :currectPlan="currectPlan"
 *   :filter="filter"
 *   :filterServer="filterServer"
 *   :openChange="openChange"
 *   :pageID="pageID"
 * />
 */
export default defineComponent({
  name: 'FilterContent',
  components: {
    TmSelectHelper,
    TmIcon,
    Field,
    TmSelect,
    TmDatePick,
    TmDateTimePick,
    TmTag,
    TmSlider,
    TmPopover,
    TmTabs,
    QTabPanel,
    TInputNumber
  },
  props: {
    plan: Object,
    currectPlan: String,
    filter: {
      type: Object,
      default: ()=>{
        return {}
      },
    },
    filterServer: Array,
    openChange: Boolean,
    pageID: String,
    filterGroups:Array,
    initedData:Object
  },
  setup(props, { emit }) {
    const { filterServer, filter, openChange, pageID,filterGroups,initedData } = toRefs(props);
    const $q = useQuasar();
    const showNotify = $q.notify;
    const filterContent = ref({
      ElementType: 'Group',
      Filters: [
        // {
        //   ElementType: 'Filter',
        //   Code: 'DO_DEP_ProjectBug.AssignTo',
        //   Condition: '=',
        //   Value: '@我',
        //   Name: '指派给',
        //   DataType: 'String',
        //   ValueName: '@我',
        //   ValueType: 0,
        // },
        // { ElementType: 'Relation', Relation: 'and' },
        // {
        //   ElementType: 'Filter',
        //   Code: 'SDO_DEP_BugState.Name',
        //   Condition: 'notcontains',
        //   Value: '已关闭',
        //   Name: '状态',
        //   DataType: 'String',
        //   ValueName: '已关闭',
        //   ValueType: 0,
        // },
        // { ElementType: 'Relation', Relation: 'and' },
        // {
        //   ElementType: 'Filter',
        //   Code: 'SDO_DEP_BugState.Name',
        //   Condition: 'contains',
        //   Value: '已处理',
        //   Name: '状态',
        //   DataType: 'String',
        //   ValueName: '已处理',
        //   ValueType: 0,
        // },
      ],
    });
    const isGroup =
      filterServer.value && filterServer.value[0]
        ? filterServer.value[0].isGroup
        : false;
    const active = ref(0);

    const getActions = actions => {
      if (actions) {
        return actions.map(item => {
          return [
            { value: '=', text:  $q.lang.queryPlan.mobile.equal },
            { value: '>', text: $q.lang.queryPlan.mobile.greaterThan},
            { value: '>=', text: $q.lang.queryPlan.mobile.greaterThanOrEqual },
            { value: '<', text: $q.lang.queryPlan.mobile.lessThan },
            { value: '<=', text: $q.lang.queryPlan.mobile.lessThanOrEqual },
            { value: '<>', text: $q.lang.queryPlan.mobile.notEqual},
            { value: 'between', text: $q.lang.queryPlan.mobile.between},
            { value: 'contains', text:  $q.lang.queryPlan.mobile.contains },
            { value: 'notcontains', text: $q.lang.queryPlan.mobile.notContains },
            { value: 'in', text: $q.lang.queryPlan.mobile.in },
            { value: 'notin', text: $q.lang.queryPlan.mobile.notin  },
            { value: 'isnotblank', text: $q.lang.dataGrid.filterOperation.isNotBlank },
            { value: 'isblank', text: $q.lang.dataGrid.filterOperation.isBlank},
            { value: '[=]', text:   `${$q.lang.queryPlan.mobile.equal}(字段)`},
            { value: '[<>]', text: `${$q.lang.queryPlan.mobile.notEqual}(字段)`},
            { value: '[<]', text: `${$q.lang.queryPlan.mobile.lessThan}(字段)`},
            { value: '[>]', text: `${$q.lang.queryPlan.mobile.greaterTha}(字段)`},
            { value: '[<=]', text: `${$q.lang.queryPlan.mobile.lessThanOrEqual}(字段)`},
            { value: '[>=]', text:`${$q.lang.queryPlan.mobile.greaterThanOrEqual}(字段)`},
          ].find(ele => ele.value == item);
        });
      } else {
        return [];
      }
      //保证加载顺序
      // return [
      //   { value: '=', text: '等于' },
      //   { value: '>', text: '大于' },
      //   { value: '>=', text: '大于等于' },
      //   { value: '<', text: '小于' },
      //   { value: '<=', text: '小于等于' },
      //   { value: '<>', text: '不等于' },
      //   { value: 'between', text: '之间' },
      //   { value: 'contains', text: '包含' },
      //   { value: 'notcontains', text: '不包含' },
      //   { value: 'in', text: '隶属' },
      //   { value: 'notin', text: '非隶属' },
      // ].filter(item => actions && actions.includes(item.value));
    };
    watch(
      () => filterContent.value,
      async () => {
        emit('update:filter', filterContent.value);
      },
      {
        deep: true,
      },
    );
    watch(
      () => active.value,
      async () => {
        await nextTick();

        offsetTop.value = refFilterContent.value.getBoundingClientRect().top;
      },
      {
        deep: true,
      },
    );
    watch(
      () => filter.value,
      async () => {
        await nextTick();

        offsetTop.value = refFilterContent.value&&refFilterContent.value.getBoundingClientRect().top;
      },
      {
        deep: true,
      },
    );
    watch(
      () => openChange.value,
      async () => {
        await nextTick();
        offsetTop.value = refFilterContent.value&&refFilterContent.value.getBoundingClientRect().top;
      },
      {
        deep: true,
      },
    );


    const needReload = ref(false);
    const searchList = ref({})
    onMounted(async () => {
      await nextTick();
      window.Proxy_Filter = {
        filterContent: filterContent.value.Filters,
        ClearRelationCondition: ClearRelationCondition,
        RelationCondition: RelationCondition,
        searchList:searchList.value
      };
      for (let i in ClearRelationCondition) {
        window.Proxy_Filter[filterContent.value.Filters.find(item => item.Code == i).Value]='watch'
        watch(
          () => filterContent.value.Filters.find(item => item.Code == i)?.Value,
          (nv,ov) => {
            if(nv==ov) return
            if(Array.isArray(nv)&&Array.isArray(ov)){
              if(JSON.stringify(nv)==JSON.stringify(ov)) return
            }
            filterContent.value.Filters.forEach((item, index) => {
              if(ClearRelationCondition[i].includes(item.Code)){
                item.Value = ''
                item.ValueName = ''
                if(searchList.value[item.Code]){
                  searchList.value[item.Code].proxySearch = searchList.value[item.Code].search()
                  searchList.value[item.Code].random = Math.random()
                  const data = searchList.value[item.Code].proxySearch;
                  let columns=[]
                  if (data instanceof Promise) {
                    data.then(res => {
                      columns = res.List;
                      columns = columns.map(element => {
                        const data = {
                          label: '',
                          value: '',
                        };
                        data.label = element[searchList.value[item.Code].labelField];
                        data.value = element[searchList.value[item.Code].valueField];
                        return data;
                      });
                      columns_action.value[item.Code]= columns;
                    });
                  } else {
                    columns = data.List;
                    columns = columns.map(element => {
                      const data = {
                        label: '',
                        value: '',
                      };
                      data.label = element[searchList.value[item.Code].labelField];
                        data.value = element[searchList.value[item.Code].valueField];
                      return data;
                    });
                    columns_action.value[item.Code] = columns;
                  }
                }
              }
            })
            setTimeout(() => {
              Filters.value=filterContent.value.Filters
            }, 100);

            // const target = filterContent.value.Filters.filter(item =>
            //   ClearRelationCondition[i].includes(item.Code),
            // );
            // if (!target.forEach) return;
            // target.forEach(element => {
            //   element.Value = '';
            //   element.ValueName = '';
            // });

          },
          {
            deep:true
          }
        );
      }
    });
    const columns_action = ref({});
    const filterMapping = ref({});
    const Filters = ref(filterContent.value.Filters) ;

    //依赖收集
    const ClearRelationCondition = {};
    const RelationCondition = {};
    // const props.initedData = ref({})
    const generateFilterContent = (item, condition) => {
      let filter_typeSetting = (item.filter_typeSetting&&JSON.parse(item.filter_typeSetting))||{};
      let defultPlaceholder =''
      let defaultStartPlaceholder = ''
      let defaultEndPlaceholder = ''
      if(filter_typeSetting.configData_placeholder&&filter_typeSetting.configData_placeholder.enablePlaceholder&&filter_typeSetting.configData_placeholder.placeholderContext){
        let res = new Function(filter_typeSetting.configData_placeholder.placeholderContext)()
        defultPlaceholder = res.placeholder
        defaultStartPlaceholder = res.startPlaceholder||''
        defaultEndPlaceholder = res.endPlaceholder||''
      }


      let _Filter =
        Filters.value[filterMapping[item.tableAlias + '.' + item.fieldCode]];
       console.log('=====filter.value=====', filter.value?.Filters);
      if (filter.value?.Filters.find(_filter => _filter.Code == _Filter.Code)) {
        _Filter =  Filters.value[
          filterMapping[item.tableAlias + '.' + item.fieldCode]
        ] = filter.value.Filters.find(_filter => _filter.Code == _Filter.Code);
      }
      const Template = [];

      if(condition=='isblank'||condition=='isnotblank'){
        Template.push( <Field
          v-model={_Filter.Value}

         textAlign='right'
          borderType='borderless'
          labelpositin='left'
          readonly={true}
        />)

        return Template
      }else if(condition&&condition.indexOf('[')!=-1){
        Template.push( <tm-select
        clearable={_Filter.Value!==''&&_Filter.Value!==null&&true}
        labelpositin='left'
          v-model={_Filter.Value}
          hideLabel={true}
          Label={$q.lang.queryPlan.subWarning.choise}
          title={$q.lang.queryPlan.subWarning.choise}
          HelpPlacement='bottom'
          placeholder={defultPlaceholder|| $q.lang.queryPlan.subWarning.choise}
          defaultValue=''
          staticItems={(()=>{
            return  Filters?.value.map(item=>{
              return {
                label:item.Name,
                value:item.Code
              }
            }).filter(item=>item.value)||[]
          })()}
          itemsDataSourceType="static"
          displayDataSource={_Filter.ValueName}
          onConfirm={e => {
            if(_Filter.Condition&&_Filter.Condition.indexOf('in')!=-1){
              _Filter.ValueName = e
            }else{
              _Filter.ValueName = e.label;
            }
          }}
          class='tr-select-enterform subCondition tr-input-editform'
          style="margin-top:0px !important"
          borderType='borderless'
         textAlign='right'
         onClear={()=>{
          _Filter.Value = '';
          _Filter.ValueName = '';
        }}
        />)
        return Template
      }
      if (condition == 'between' ) {
        if(typeof _Filter.Value == 'string'&& _Filter.Value .indexOf('-')!=-1){
          _Filter.Value =_Filter.Value.split('-')
        }else if(! _Filter.Value){
          _Filter.Value = ['', ''];
        }

      } else if (
        condition != 'between' &&
        _Filter.Value &&
        _Filter.Value.push
      ) {
        if(condition=='in'||condition=='notin'){
          if(!Array.isArray(_Filter.Value)){
            _Filter.Value =  _Filter.Value&&_Filter.Value.split(',')||[]
          _Filter.ValueName =  _Filter.ValueName&& _Filter.ValueName.split(',')||[]
          }

        }else{
          _Filter.Value = '';
        }

      }
      if (item.filter_classicConfig) {
        const filter_classicConfig =
          item.filter_classicConfig instanceof Object
            ? item.filter_classicConfig
            : JSON.parse(item.filter_classicConfig);
        const initData =
          filter_classicConfig.InitValue instanceof Function
            ? filter_classicConfig.InitValue()
            : filter_classicConfig.InitValue;
        if(!initedData.value.firstPlanId){
          initedData.value.firstPlanId=props.currectPlan.ID
        }else if(initedData.value.firstPlanId!=props.currectPlan.ID){
          initedData.value.currectPlanId = props.currectPlan.ID
          delete initedData.value[_Filter.Code]
        }
        if (
          filter_classicConfig.InitValue &&
          !(_Filter.Value && _Filter.ValueName) &&
          initData&&props.currectPlan.IsSystem&&
          !initedData.value[_Filter.Code]
          //&&initedData.value.firstPlanId==props.currectPlan.ID&&!initedData.value.currectPlanId
        ) {
          initedData.value[_Filter.Code]=true
          _Filter.Value = initData.Value ;
          _Filter.ValueName = initData.Name;
          if(_Filter.Condition=='between'&&_Filter.Value&&!Array.isArray(_Filter.Value)){
            _Filter.Value=_Filter.Value.split('-')
          }
          emit('update:filterGroups',filterGroups.value, _Filter);
        }
        //关联字段清空
        if (filter_classicConfig.DependCodes.length > 0) {
          filter_classicConfig.DependCodes.forEach(element => {
            if (!ClearRelationCondition[element]) {
              ClearRelationCondition[element] = [
                `${item.tableAlias}.${item.fieldCode}`,
              ];
            } else {
              if (
                !ClearRelationCondition[element].includes(
                  `${item.tableAlias}.${item.fieldCode}`,
                )
              ) {
                ClearRelationCondition[element].push(
                  `${item.tableAlias}.${item.fieldCode}`,
                );
              }
            }
          });

          //关联字段非空校验
          if (filter_classicConfig.IsCompDepend) {
            if (!RelationCondition[`${item.tableAlias}.${item.fieldCode}`]) {
              RelationCondition[`${item.tableAlias}.${item.fieldCode}`] =
                filter_classicConfig.DependCodes;
            } else {
              filter_classicConfig.DependCodes.forEach(element => {
                if (
                  !RelationCondition[
                    `${item.tableAlias}.${item.fieldCode}`
                  ].includes(element)
                ) {
                  RelationCondition[
                    `${item.tableAlias}.${item.fieldCode}`
                  ].push(element);
                }
              });
            }
          }
        }
      }
      switch (item.filter_inputWay) {
        case 'text':
          let isNumber = false;
          if (
            item.dataType == 'Int' ||
            item.dataType == 'Decimal' ||
            item.dataType == 'Number' ||
            item.dataType == 'number' ||
            item.dataType == 'Long'
          ) {
            isNumber = true;
          }
          if (condition == 'between') {
            if(!_Filter.Value){
              _Filter.Value=[]
            }
            if (isNumber && item.filter_typeSetting) {
              try {

                //滑块模式
                if (filter_typeSetting.showType == 1) {
                  Template.push(
                    <div style='height:24px;display:flex;align-item:center'>
                      <tm-slider
                      borderLesss={true}
                        range
                        v-model={_Filter.Value}
                        hideLabel={true}
                        onChange={()=>{

                         ! _Filter.Condition? _Filter.Condition = '=':''
                       }}
                        style={
                          filter_typeSetting.showPosition
                            ? 'width:100%'
                            : 'width:100%'
                        }
                        step={
                          filter_typeSetting.limitSize
                            ? filter_typeSetting.step
                            : 1
                        }
                        max={
                          filter_typeSetting.max ? filter_typeSetting.max : 100
                        }
                        min={
                          filter_typeSetting.min ? filter_typeSetting.min : 0
                        }
                      >
                        {{
                          button: () => {
                            if (filter_typeSetting.showPosition) {
                              return '';
                            }
                            return (
                              <div style=' width: 26px;color: #fff;font-size: 10px;line-height: 18px;text-align: center;background-color: var(--tm-primary-color);border-radius: 100px;'>
                                {_Filter.Value}
                              </div>
                            );
                          },
                        }}
                      </tm-slider>
                    </div>,
                  );
                  return Template;
                }else{
                  Template.push(
                    <div class='_between _between_center' style='flex: 1 1 auto;width: 100%;display: flex;align-items: center;justify-content: center;text-align: center;'>
                      <TInputNumber
                      max={
                        filter_typeSetting.max ? filter_typeSetting.max : 100
                      }
                      min={
                        filter_typeSetting.min ? filter_typeSetting.min : 0
                      }
                      accuracy={
                        filter_typeSetting.precision ? filter_typeSetting.precision : 0
                      }
                    v-model={_Filter.Value[0]}
                    placeholder={defaultStartPlaceholder|| $q.lang.queryPlan.title.pleaseEnter}
                   textAlign='center'
                    borderType='borderless'
                    labelpositin='left'

                  />
                  <span> - </span>
                  <TInputNumber
                    accuracy={
                      filter_typeSetting.precision ? filter_typeSetting.precision : 0
                    }
 max={
  filter_typeSetting.max ? filter_typeSetting.max : 100000000
}
min={
  _Filter.Value[0]||( filter_typeSetting.min ? filter_typeSetting.min : 0)
}
                  borderLesss={true}
                    v-model={_Filter.Value[1]}
                    placeholder={defaultEndPlaceholder|| $q.lang.queryPlan.title.pleaseEnter}
                   textAlign='center'
                    labelpositin='left'
                    borderType='borderless'
                  />
                    </div>,
                  );
                }
                // return;
              } catch (error) {
                console.log(error);
              }
            }else if(isNumber){
              Template.push(
                <div class='_between _between_center' style={'flex: 1 1 auto;width: 100%;display: flex;align-items: center;justify-content: center;text-align: center;'}>
                  <TInputNumber
  accuracy={
    filter_typeSetting.precision ? filter_typeSetting.precision : 0
  }
                    v-model={_Filter.Value[0]}
                    placeholder={defaultStartPlaceholder|| $q.lang.queryPlan.title.pleaseEnter}
                   textAlign='center'
                    borderType='borderless'
                    labelpositin='left'
                    max={
                      filter_typeSetting.max ? filter_typeSetting.max : 100
                    }
                    min={
                      filter_typeSetting.min ? filter_typeSetting.min : 0
                    }
                  />
                  <span> - </span>
                  <TInputNumber
                    accuracy={
                      filter_typeSetting.precision ? filter_typeSetting.precision : 0
                    }
  max={
    filter_typeSetting.max ? filter_typeSetting.max : 100000000
  }
  min={
    _Filter.Value[0]||( filter_typeSetting.min ? filter_typeSetting.min : 0)
  }
                  borderLesss={true}
                    v-model={_Filter.Value[1]}
                    placeholder={defaultEndPlaceholder|| $q.lang.queryPlan.title.pleaseEnter}
                   textAlign='center'
                    labelpositin='left'
                    borderType='borderless'
                  />
                </div>,
              );
            }else{
              Template.push(
                <div class='_between'>
                  <Field
                    v-model={_Filter.Value[0]}
                    placeholder={defaultStartPlaceholder|| $q.lang.queryPlan.title.pleaseEnter}
                   textAlign='right'
                    borderType='borderless'
                    labelpositin='left'

                  />
                  <span> - </span>
                  <Field

                  borderLesss={true}
                    v-model={_Filter.Value[1]}
                    placeholder={defaultEndPlaceholder|| $q.lang.queryPlan.title.pleaseEnter}
                   textAlign='right'
                    labelpositin='left'
                    borderType='borderless'
                  />
                </div>,
              );
            }

          } else {
            if (isNumber && item.filter_typeSetting) {
              try {

                //滑块模式
                if (filter_typeSetting.showType == 1) {
                  Template.push(
                    <div style='height:24px;display:flex;align-item:center'>
                      <tm-slider
                      borderLesss={true}
                        v-model={_Filter.Value}
                        labelpositin='left'
                        hideLabel={true}
                        onChange={()=>{

                          ! _Filter.Condition? _Filter.Condition = '=':''
                        }}
                        style={
                          filter_typeSetting.showPosition
                            ? 'width:calc(100% - 28px);margin-left:14px'
                            : ''
                        }
                        step={
                          filter_typeSetting.limitSize
                            ? filter_typeSetting.step
                            : 1
                        }
                        max={
                          filter_typeSetting.max ? filter_typeSetting.max : 100
                        }
                        min={
                          filter_typeSetting.min ? filter_typeSetting.min : 0
                        }
                      >
                        {{
                          button: () => {
                            if (filter_typeSetting.showPosition) {
                              return '';
                            }
                            return (
                              <div style=' width: 26px;color: #fff;font-size: 10px;line-height: 18px;text-align: center;background-color: var(--tm-primary-color);border-radius: 100px;'>
                                {_Filter.Value}
                              </div>
                            );
                          },
                        }}
                      </tm-slider>
                    </div>,
                  );
                  return Template;
                }else{
                  Template.push(


                    <TInputNumber
                      labelpositin='left'
                      v-model={_Filter.Value}
                      accuracy={
                        filter_typeSetting.precision ? filter_typeSetting.precision : 0
                      }
                      onChange={()=>{
                        _Filter.ValueName = _Filter.Value
                       ! _Filter.Condition? _Filter.Condition = '=':''

                      }}
                      max={
                        filter_typeSetting.max ? filter_typeSetting.max : 100
                      }
                      min={
                        filter_typeSetting.min ? filter_typeSetting.min : 0
                      }
                      placeholder={defultPlaceholder|| $q.lang.queryPlan.title.pleaseEnter}
                      borderType='borderless'
                     textAlign='right'
                    />
                  );
                }
              } catch (error) {
                console.log(error);
              }
            }else if(isNumber){
              Template.push(


                <TInputNumber
                  labelpositin='left'
                  v-model={_Filter.Value}
                  accuracy={
                    filter_typeSetting.precision ? filter_typeSetting.precision : 0
                  }
                  onChange={()=>{
                    _Filter.ValueName = _Filter.Value
                   ! _Filter.Condition? _Filter.Condition = '=':''

                  }}
                  max={
                    filter_typeSetting.max ? filter_typeSetting.max : 100
                  }
                  min={
                    filter_typeSetting.min ? filter_typeSetting.min : 0
                  }
                  placeholder={defultPlaceholder|| $q.lang.queryPlan.title.pleaseEnter}
                  borderType='borderless'
                 textAlign='right'
                />
              );
                        }else{
                          Template.push(
                            <Field
                              labelpositin='left'
                              v-model={_Filter.Value}
                              onChange={()=>{
                                _Filter.ValueName = _Filter.Value
                               ! _Filter.Condition? _Filter.Condition = '=':''

                              }}
                              placeholder={defultPlaceholder|| $q.lang.queryPlan.title.pleaseEnter}
                              borderType='borderless'
                             textAlign='right'
                            />
                          );

                        }
          }

          break;
        case 'help':


          Template.push(
            <tm-select-helper
            class="tr-input-editform"
            borderType='borderless'
              labelpositin='left'
              v-model:value={_Filter.Value}
              v-model:text={_Filter.ValueName}
              borderLesss={true}
              countPerPage={10}
              helpConf={false}
              placeholder={defultPlaceholder|| $q.lang.queryPlan.subWarning.choise}
              multiple={_Filter.Condition&&_Filter.Condition.indexOf('in')!=-1?true:false}
              search={item.search ? item.search : () => {}}
              opening={e => {

                if (RelationCondition[_Filter.Code]) {
                  for (const i in RelationCondition[_Filter.Code]) {
                    if (
                      !filter.value.Filters.find(
                        item =>
                          item.Code == RelationCondition[_Filter.Code][i] &&
                          item.Value,
                      )
                    ) {
                      Funcs.Notify($q.lang.selectHelper.warning, `【${
                        filterContent.value.Filters.find(
                          item =>
                            item.Code == RelationCondition[_Filter.Code][i],
                        ).Name
                      }】条件必须存在，请设置`, 'warning')
                      // showNotify({
                      //   message: `【${
                      //     filterContent.value.Filters.find(
                      //       item =>
                      //         item.Code == RelationCondition[_Filter.Code][i],
                      //     ).Name
                      //   }】条件必须存在，请设置`,
                      //   type: 'warning',
                      // });
                      e.cancel=true
                      return false;
                    }
                  }
                }
                e.cancel=false
                return true;
              }}
              simple={true}
              labelField={
                item.filter_dataValue
                  ? JSON.parse(item.filter_dataValue).labelField
                  : ''
              }
              valueMapping={
                item.filter_dataValue
                  ? JSON.parse(item.filter_dataValue).valueField
                  : ''
              }
              displayMapping={
                item.filter_dataValue
                  ? JSON.parse(item.filter_dataValue).labelField
                  : ''
              }
              valueField={
                item.filter_dataValue
                  ? JSON.parse(item.filter_dataValue).valueField
                  : ''
              }
              height='80%'
              onConfirm={e => {
                if (item.afterLoad) {
                  item.afterLoad(e);
                }

                if(_Filter.Condition&&_Filter.Condition.indexOf('in')!=-1){
                  _Filter.ValueName =  _Filter.Value = e.map(items=>{
                    let res = {}
                    res[item.filter_dataValue?JSON.parse(item.filter_dataValue).labelField:''] = items[item.filter_dataValue?JSON.parse(item.filter_dataValue).labelField:'']
                    res[item.filter_dataValue?JSON.parse(item.filter_dataValue).valueField:''] = items[item.filter_dataValue?JSON.parse(item.filter_dataValue).valueField:'']
                    res.label= items[item.filter_dataValue?JSON.parse(item.filter_dataValue).labelField:'']
                    res.value = items[item.filter_dataValue?JSON.parse(item.filter_dataValue).valueField:'']

                    return res
                  })
                  return
                }
               ! _Filter.Condition? _Filter.Condition = '=':''
              }}
              helperCode='abcdefj'
              historyEnable={false}
              iconEnable={false}
              iconFiled='Avatar'
              iconDataSource='Avatar'
              unit=''
              searchEnable={true}
              searchPosition='bottom'
              openType="bottom"
              hideLabel={true}
             textAlign='right'
              pagination={true}

            ></tm-select-helper>,
          );
          break;
        case 'down':
          if (item.filter_dataType != 'action') {
            let columns = item.filter_dataValue.split(',');
            columns = columns.map(element => {
              const data = {
                label: '',
                value: '',
              };
              data.label = element.split(':')[1];
              data.value = element.split(':')[0];
              return data;
            });
            if (item.filter_showType == 'tile') {
              Template.push(
                <div style={'margin-top:21px'}>
                  {(() => {
                    const Tem = [];
                    for (let i = 0; i < columns.length; i++) {
                      Tem.push(

                        <tm-tag
                          v-model={_Filter.Value}
                          square
                          size='20px'
                          selected={_Filter.Value == columns[i].value}
                          onClick={() => {
                            if (_Filter.Value == columns[i].value) {
                              _Filter.Value = '';
                              _Filter.ValueName = '';
                              ! _Filter.Condition? _Filter.Condition = '=':''
                              return;
                            }
                            _Filter.Value = columns[i].value;
                            _Filter.ValueName = columns[i].label;
                            ! _Filter.Condition? _Filter.Condition = '=':''
                          }}
                        >
                          <span

                          >
                            {columns[i].label}
                          </span>
                        </tm-tag>,
                        // <span
                        //   onClick={() => {
                        //     _Filter.Value = columns[i].value;
                        //   }}
                        // >

                        // </span>,
                      );
                    }
                    return Tem;
                  })()}
                </div>,
              );
            } else {

              if(_Filter.Condition&&_Filter.Condition.indexOf('in')!=-1){
                if(!_Filter.Value&& _Filter.Value!==0&&_Filter.Value!=='0'){
                  _Filter.Value = []
                }else if(!Array.isArray(_Filter.Value)){
                  _Filter.Value = (_Filter.Value+'').split(',')
                }

              }
              Template.push(
                <tm-select
                clearable={_Filter.Value!==''&&_Filter.Value!==null}
                multiple={_Filter.Condition&&_Filter.Condition.indexOf('in')!=-1?true:false}
                labelpositin='left'
                  use-input={false}
                  class={"tr-select-enterform subCondition tr-input-editform" }
                  v-model:modelValue={_Filter.Value}
                  hideLabel={true}
                  Label={$q.lang.queryPlan.subWarning.choise}
                  title={$q.lang.queryPlan.subWarning.choise}
                  HelpPlacement='bottom'
                  placeholder={defultPlaceholder|| $q.lang.queryPlan.subWarning.choise}
                  defaultValue=''
                  staticItems={columns}
                  itemsDataSourceType="static"
                  displayDataSource={_Filter.ValueName}
                  onConfirm={e => {
                    if(_Filter.Condition&&_Filter.Condition.indexOf('in')!=-1){
                      _Filter.ValueName = e
                    }else{
                      _Filter.ValueName = e.label;
                    }

                    ! _Filter.Condition? _Filter.Condition = '=':''
                  }}
                  itemsDataSourceType='static'
                 textAlign='right'
                  borderType='borderless'
                  opening={(e)=>{
                    if (RelationCondition[_Filter.Code]) {
                      for (const i in RelationCondition[_Filter.Code]) {
                        if (
                          !filter.value.Filters.find(
                            item =>
                              item.Code == RelationCondition[_Filter.Code][i] &&
                              item.Value,
                          )
                        ) {
                          Funcs.Notify($q.lang.selectHelper.warning , $q.lang.queryPlan.mobile.filterRelationCheck.format(filterContent.value.Filters.find( item => item.Code == RelationCondition[_Filter.Code][i],).Name), 'warning')

                          e.cancel=true
                          return false;
                        }
                      }
                    }
                    e.cancel=false
                    return true;
                  }}
                  onClear={()=>{
                    _Filter.Value = '';
                    _Filter.ValueName = '';
                  }}

                />,
              );
            }
          } else {
            const labelField = item.filter_dataValue
              ? JSON.parse(item.filter_dataValue).labelField
              : '';
            const valueField = item.filter_dataValue
              ? JSON.parse(item.filter_dataValue).valueField
              : '';
            let columns = columns_action.value[`${item.tableAlias}.${item.fieldCode}`];
            if (!columns) {
              columns = [];
              if(!searchList.value[`${item.tableAlias}.${item.fieldCode}`]){
                searchList.value[`${item.tableAlias}.${item.fieldCode}`]={
                  proxySearch:item.search(),
                  search:item.search,
                  random : Math.random(),
                  labelField,
                  valueField
                }
              }
              const data = searchList.value[`${item.tableAlias}.${item.fieldCode}`].proxySearch;
              if (data instanceof Promise) {
                data.then(res => {
                  columns = res.List;
                  columns = columns.map(element => {
                    const data = {
                      label: '',
                      value: '',
                    };
                    data.label = element[labelField];
                    data.value = element[valueField];
                    return data;
                  });
                  columns_action.value[`${item.tableAlias}.${item.fieldCode}`] = columns;
                });
              } else {
                columns = data.List;
                columns = columns.map(element => {
                  const data = {
                    label: '',
                    value: '',
                  };
                  data.label = element[labelField];
                  data.value = element[valueField];
                  return data;
                });
                columns_action.value[`${item.tableAlias}.${item.fieldCode}`] = columns;
              }
            }

            if (item.filter_showType == 'tile') {
              Template.push(
                <div>
                  {(() => {
                    const Tem = [];
                    for (let i = 0; i < columns.length; i++) {
                      Tem.push(
                        <tm-tag
                          v-model={_Filter.Value}
                          plain
                          type='primary'
                          size='small'
                          style={
                            _Filter.ValueName != columns[i].label
                              ? 'margin-right:12px;padding:4px 12px;margin-bottom:8px;background:#F4F4F5;color: rgba(0, 0, 0, var(--t-color-opacity, /*批量处理90%透明度*/0.9));border:0;outline:0'
                              : 'margin-right:12px;padding:4px 12px;margin-bottom:8px;background:var(--q-primary)!important;color:#fff'
                          }

                        >
                          <span
                           onClick={() => {
                            if (_Filter.Value == columns[i].value) {
                              _Filter.Value = '';
                              _Filter.ValueName = '';
                             ! _Filter.Condition? _Filter.Condition = '=':''
                              return;
                            }
                            _Filter.Value = columns[i].value;
                            _Filter.ValueName = columns[i].label;
                            ! _Filter.Condition? _Filter.Condition = '=':''
                          }}
                          >
                            {columns[i].label}
                          </span>

                          {/* <span
                            v-show={_Filter.ValueName == columns[i].label}
                            class={
                              _Filter.ValueName == columns[i].label
                                ? 'select'
                                : ''
                            }
                          >
                            <tm-icon
                              name='success'
                              color='#fff'
                              style='    position: absolute;bottom: -1px; right: -2px;transform: scale(.8) rotate(-30deg);'
                            ></tm-icon>
                          </span> */}
                        </tm-tag>,
                        // <span
                        //   onClick={() => {
                        //     _Filter.Value = columns[i].value;
                        //   }}
                        // >

                        // </span>,
                      );
                    }
                    return Tem;
                  })()}
                </div>,
              );
            } else {
              if(_Filter.Condition&&_Filter.Condition.indexOf('in')!=-1){

                if(!_Filter.Value&& _Filter.Value!==0&&_Filter.Value!=='0'){
                  _Filter.Value = []
                }else if(!Array.isArray(_Filter.Value)){

                  _Filter.Value = (_Filter.Value+'').split(',')

                }

              }
              Template.push(
                <tm-select
                clearable={_Filter.Value!==''&&_Filter.Value!==null}
                labelpositin='left'
                  v-model={_Filter.Value}
                  multiple={_Filter.Condition&&_Filter.Condition.indexOf('in')!=-1?true:false}
                  hideLabel={true}
                  Label={$q.lang.queryPlan.subWarning.choise}
                  title={$q.lang.queryPlan.subWarning.choise}
                  HelpPlacement='bottom'
                  placeholder={defultPlaceholder|| $q.lang.queryPlan.subWarning.choise}
                  defaultValue=''
                  staticItems={ columns_action.value[`${item.tableAlias}.${item.fieldCode}`]}
                  itemsDataSourceType="static"
                  displayDataSource={_Filter.ValueName}
                  onConfirm={e => {
                    if(_Filter.Condition&&_Filter.Condition.indexOf('in')!=-1){
                      _Filter.ValueName = e
                    }else{
                      _Filter.ValueName = e.label;
                    }
                   ! _Filter.Condition? _Filter.Condition = '=':''
                  }}
                  class='tr-select-enterform subCondition tr-input-editform'
                  style="margin-top:0px !important"
                  borderType='borderless'
                 textAlign='right'
                  opening={(e)=>{
                    if (RelationCondition[_Filter.Code]) {
                      for (const i in RelationCondition[_Filter.Code]) {
                        if (
                          !filter.value.Filters.find(
                            item =>
                              item.Code == RelationCondition[_Filter.Code][i] &&
                              item.Value,
                          )
                        ) {
                          Funcs.Notify($q.lang.selectHelper.warning , $q.lang.queryPlan.mobile.filterRelationCheck.format(filterContent.value.Filters.find( item => item.Code == RelationCondition[_Filter.Code][i],).Name), 'warning')
                          e.cancel=true
                          return false;
                        }
                      }
                    }
                    e.cancel=false
                    return true;
                  }}
                  onClear={()=>{
                    _Filter.Value = '';
                    _Filter.ValueName = '';
                  }}
                />,
              );
            }

          }
          break;
        case 'date':
        case 'time':

          if (item.dataType == 'Date') {
            if (condition == 'between') {
              if(!_Filter.Value){
                _Filter.Value=[]
              }
              Template.push(
                <tm-date-pick displayFormatWithDateTime="'YYYY/MM/DD'"
                valueFormat="YYYY/MM/DD" v-model:modelValue={_Filter.Value}
              dateType="daterange"
              onChange={()=>{
                _Filter.ValueName = _Filter.Value.join(' - ')
              }}
                range={true} format24h={true} clearable={true} style={`flex: none;width: 100%;`}/>
                // <div class='_between'>

                //  <tm-date-pick

                //     defaultYearMonth={new Date()}

                //     v-model={_Filter.Value[0]}
                //     borderType="borderless"
                //     class='tr-datetime-div'
                //     displayFormatWithDate="YYYY/MM/DD"
                //     placeholder={filter_typeSetting.startPlaceholder}

                //   />
                //   <span> - </span>
                //   <tm-date-pick

                //     v-model={_Filter.Value[1]}
                //     defaultYearMonth={new Date()}

                //     borderType="borderless"
                //     class='tr-datetime-div'
                //     displayFormatWithDate="YYYY/MM/DD"
                //     placeholder={filter_typeSetting.startPlaceholder}

                //   />
                // </div>,
              );
            } else {
              Template.push(
                <tm-date-pick
                labelpositin='left'
                  v-model={_Filter.Value}
                  defaultYearMonth={new Date()}
                  dateType='date'
                  borderType='borderless'
                  class='tr-datetime-div'
                  displayFormatWithDate="YYYY/MM/DD"
                  placeholder={defultPlaceholder|| filter_typeSetting.startPlaceholder}
                  onChange={()=>{
                    _Filter.ValueName = _Filter.Value
                  }}
                />,
              );
            }
          } else {
            if (condition == 'between') {
              if(!_Filter.Value){
                _Filter.Value=[]
              }
              Template.push(
                <tm-date-pick displayFormatWithDateTime="YYYY/MM/DD HH:mm:ss"
                valueFormat="YYYY/MM/DD HH:mm:ss" v-model:modelValue={_Filter.Value}
              dateType="datetimerange"
              onChange={()=>{
                _Filter.ValueName = _Filter.Value.join(' - ')
              }}
                range={true} format24h={true} clearable={true} style={`flex: none;width: 100%;`}/>
                // <div class='_between'>

                //   {/* <tm-date-pick
                //     v-model={_Filter.Value[0]}
                //     borderType="borderless"
                //     class='tr-datetime-div'
                //     defaultYearMonth={new Date()}
                //     displayFormatWithDate="YYYY/MM/DD"
                //     placeholder={filter_typeSetting.startPlaceholder}
                //   />
                //   <span> - </span>
                //   <tm-date-pick

                //     v-model={_Filter.Value[1]}
                //     borderLesss={true}
                //     defaultYearMonth={new Date()}
                //     borderType="borderless"
                //     class='tr-datetime-div'
                //     displayFormatWithDate="YYYY/MM/DD"
                //     placeholder={filter_typeSetting.endPlaceholder}
                //   /> */}
                // </div>,
              );
            } else {
              Template.push(
                <tm-date-pick
                  v-model={_Filter.Value}
                  defaultYearMonth={new Date()}
                   dateType='datetime'
                  borderType="borderless"
                  class='tr-datetime-div'
                  displayFormatWithDate="YYYY/MM/DD"
                  placeholder={defultPlaceholder|| filter_typeSetting.startlaceholder}
                  onChange={()=>{
                    _Filter.ValueName = _Filter.Value
                  }}

                />,
              );
            }
          }

          break;
        case 'date':
      }

      return Template;
    };

    const _filterColumns = filterServer.value
      .filter(item => item.isQuery)
      .slice(0);

    const _filterColumns_group = {};
    if (isGroup) {

      _filterColumns.forEach(item => {
        if (item.ColumnCategoryInfos) {
          if (!_filterColumns_group[item.ColumnCategoryInfos.Name]) {
            _filterColumns_group[item.ColumnCategoryInfos.Name] = [];
          }
          _filterColumns_group[item.ColumnCategoryInfos.Name].push(item);
        } else {
          if (!_filterColumns_group[ $q.lang.queryPlan.mobile.other]) {
            _filterColumns_group[$q.lang.queryPlan.mobile.other] = [];
          }
          _filterColumns_group[$q.lang.queryPlan.mobile.other].push(item);
        }
      });
    }
    _filterColumns.forEach((item, index) => {
      if (
        filter.value&&filter.value.Filters &&
        filter.value.Filters.some(
          _filters => _filters.Code == item.tableAlias + '.' + item.fieldCode,
        )
      ) {
        Filters.value.push(
          filter.value.Filters.find(
            _filters => _filters.Code == item.tableAlias + '.' + item.fieldCode,
          ),
        );
      } else {
        let Condition = getActions(item.field_condition)[0]?.value;
        if (!Condition) Condition = '=';
        Filters.value.push({
          ElementType: 'Filter',
          Code: item.tableAlias + '.' + item.fieldCode,
          Condition: Condition,
          Value:null,
          Name: item.fieldName,
          DataType: item.dataType,
          ValueName: '',
          ValueType: 0,
        });
      }

      filterMapping[item.tableAlias + '.' + item.fieldCode] =
      Filters.value.length - 1;
      if (_filterColumns.length - 1 != index) {
        Filters.value.push({
          ElementType: 'Relation',
          Relation: 'and',
        });
      }
    });
    const generateFilter = () => {
      const Template = [];
      if (isGroup) {
        {
          (() => {
            let index = 0;
            for (const i in _filterColumns_group) {
              index++;
              let _generateFilterFieldContent = generateFilterFieldContent(_filterColumns_group[i])
              Template.push(
                // 生成tab内容区域
                <q-tab-panel name={(index-1)+''} title={i} >
                  <div class={'queryplan_m_filter_group'}>
                    {_generateFilterFieldContent}
                  </div>
                </q-tab-panel>,
              );
            }
          })();
        }
        console.log('Template', Template);
        return (
          <tm-tabs
            v-model:modelValue={active.value}
            scrollspy
            sticky
            offset-top={offsetTop.value}
            onScroll={() => {
              offsetTop.value =
                refFilterContent.value.getBoundingClientRect().top;
            }}
            style="flex:1 1 auto"
            staticItems={(() => {
              return Object.keys(_filterColumns_group).map((item, index) => {
                return {
                  label: item,
                  code: index+'',
                };
              });
            })()}
          >

            {Template}
          </tm-tabs>
        );
      }
      return generateFilterFieldContent(_filterColumns);
    };
    const quickItemsForDateTime = target => {
      let items = [
        {
          label: `@${Terms.date.today}`,
          value: '@今天',
        },
        {
          label: `@${Terms.date.yesterday}`,
          value: '@昨天',
        },
        {
          label: `@${Terms.date.last3day}`,
          value: '@近3天',
        },
        {
          label: `@${Terms.date.last7day}`,
          value: '@近7天',
        },
        {
          label: `@${Terms.date.thisWeek}`,
          value: '@本周',
        },
        {
          label: `@${Terms.date.lastWeek}`,
          value: '@上周',
        },
        {
          label: `@${Terms.date.thisMonth}`,
          value: '@本月',
        },
        {
          label: `@${Terms.date.lastMonth}`,
          value: '@上月',
        },
        {
          label: `@${Terms.date.thisYear}`,
          value: '@今年',
        },
        {
          label: `@${Terms.date.lastYear}`,
          value: '@上年',
        },
      ];
      const handleClick = (itemValue, itemLabel) => {
        target.Value = itemLabel;
        target.ValueName = itemValue;
      };
      return (
        <ul
          style='width:100%;display: flex;gap: 8px;justify-content: flex-start;flex-wrap: wrap;margin-top: 8px;'
          class='quickItemsUl'
        >
          {items.map((item, index) => {
            return (
              <li
                class={target.Value == item.value ? 'quickItemsActive' : ''}
                onClick={() => handleClick(item.value, item.label)}
              >
                <span>{item.label}</span>
              </li>
            );
          })}
        </ul>
      );
    };
    const generateFilterFieldContent = _filterColumns => {
      const Template = [];
      _filterColumns.forEach(item => {
        if (item.isQuery) {
          const _Filter =
          Filters.value[
            filterMapping[
              item.tableAlias + '.' + item.fieldCode
            ]
          ];

          let target = filterGroups.value?.find&&filterGroups.value?.find(items=>items.Code==(item.tableAlias + '.' + item.fieldCode))
          if (!target) target = item;

          let dateTimeCondition =
            ((_Filter.Condition == 'between' ||
              getActions([target.Condition])[0]?.value == 'between') &&
              (item.filter_inputWay == 'time' ||
                item.filter_inputWay == 'date' ||
                item.filter_inputWay == 'datetime'));
          Template.push(
            // 移动端日期时间组件增加快捷选项
            // <div style={`display: flex ;align-items: center;border-bottom: 1px solid #E4E4E4;${(_Filter.Condition=='between'||getActions([target.Condition])[0]?.value=='between')&&( item.filter_inputWay=='time'||item.filter_inputWay=='date'||item.filter_inputWay=='datatime')?'flex-wrap:wrap;padding-top:10px':'gap: 8px;'}`}>
            <div
              style={`display: flex ;align-items: center;border-bottom: 1px solid #E4E4E4;${dateTimeCondition ? 'flex-wrap:wrap;flex-direction: column;padding-top:10px;align-items: start;' : 'gap: 8px;'}`}
            >
              <p
                class='header'
                style={'flex:none;display: flex;align-items: center;'}
              >
                {/* {item.fieldName} */}
                <span
                  style={
                    'display: inline-block; overflow: hidden;text-overflow: ellipsis;line-clamp: 2; max-width:100px'
                  }
                >
                  {(() => {
                    if (item.ValueInfo_fieldName) {
                      return Funcs.GetTerms(
                        item.ValueInfo_fieldName.ReferenceExpr,
                        item.fieldName,
                      );
                    }
                    return item.fieldName;
                  })()}
                </span>

                {(() => {
                  if (target?.Condition != _Filter.Condition) {
                    if (!item.field_condition) item.field_condition = [];
                    if (
                      !item.field_condition.includes(target?.Condition) &&
                      target?.Condition
                    ) {
                      item.field_condition.push(target?.Condition);
                      if (!item.field_condition.includes('=')) {
                        item.field_condition.push('=');
                      }
                    }
                    // if(!item.field_condition.includes(_Filter.Condition)){
                    //   item.field_condition.push(_Filter.Condition)
                    // }
                  }
                  //注意事项：原则上，只有数值类的可以修改筛选规则，其他类型不允许；去掉底部button区域所有“取消”，筛选条件tab下增加“重置
                  if (
                    item.field_condition &&
                    item.field_condition.length > 0 &&
                    (item.dataType == 'Int' ||
                      item.dataType == 'Decimal' ||
                      item.dataType == 'Number' ||
                      item.dataType == 'number' ||
                      item.dataType == 'Long')
                  ) {
                    return (
                      <tm-popover
                        v-model:show={item.showPopover}
                        actions={getActions(item.field_condition, item)}
                        onSelect={e => {
                          if (_Filter.Condition == e.value) return;

                          if (e.value == 'isblank') {
                            _Filter.Condition = '=';
                            _Filter.Value = '';
                            _Filter.ValueName = '';
                          } else if (e.value == 'isnotblank') {
                            _Filter.Condition = '<>';
                            _Filter.Value = '';
                            _Filter.ValueName = '';
                          } else {
                            _Filter.Condition = e.value;
                            _Filter.Value = '';
                            _Filter.ValueName = '';
                          }

                          setTimeout(() => {
                            if (target) {
                              target.Condition = e.value;
                              target.Value = '';
                              target.ValueName = '';
                              let index = filterGroups.value.findIndex(
                                item => item.Code == target.Code,
                              );
                              filterGroups.value[index].Condition = e.value;
                              filterGroups.value[index].Value = '';
                              filterGroups.value[index].ValueName = '';
                              emit(
                                'update:filterGroups',
                                filterGroups.value,
                                target,
                              );
                            }
                          }, 10);
                        }}
                        class='filter_contion_popover'
                        style='z-index:1000;font-size:12px;text-align:left;max-height:300px;margin: 0;padding: 0;width: auto;min-width: 0;'
                        teleport={(() => {
                          return document.body;
                        })()}
                      >
                        {{
                          reference: () => {
                            return (
                              <i
                                onClick={e => {
                                  item.showPopover = true;
                                  e.stopPropagation();
                                  e.preventDefault();
                                  return false;
                                }}
                                style='background: #F7F8FB;min-width:44px;padding:8px 2px;border-radius:4px;font-style: normal;;margin-left:4px;font-size:10px;color:rgba(0,0,0,.56)'
                              >
                                {(() => {
                                  return getActions([
                                    target.Condition || item.field_condition[0],
                                  ])[0]?.text;
                                })()}
                              </i>
                            );
                          },
                        }}
                      </tm-popover>
                    );
                  }
                })()}
              </p>
              <div
                style={
                  dateTimeCondition
                    ? 'display:flex;width:100%;'
                    : 'display:none'
                }
              >
                {quickItemsForDateTime(_Filter)}
              </div>
              {generateFilterContent(
                item,
                target?.Condition || _Filter.Condition,
              )}
              {/*  */}
            </div>,
          );
        }
      });
      return Template;
    };
    //算一下offsetTop距离
    const offsetTop = ref(0);
    const refFilterContent = ref(null);

    const render = () => {
      return (
        <div class='filterContent tr-input-form' style='padding:0;' ref={refFilterContent}>

          {generateFilter()}

        </div>
      );
    };
    return render;
  },
});
